package cn.stylefeng.guns.base.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author dyf
 * @version 1.0
 * @date 2020/7/31 9:08
 * @description
 */
@Service
public class RedisUtil {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * @param key:key
     * @param object:缓存数据
     * @param cacheTime:缓存时间
     */
    public void setObject(String key, Object object,Integer cacheTime) {

        if (null!=cacheTime){
            redisTemplate.opsForValue().set(key, object, cacheTime, TimeUnit.SECONDS);
        }else {
            redisTemplate.opsForValue().set(key, object);
        }
    }

    public Object getObject(String key) {
        return redisTemplate.boundValueOps(key).get();
    }
    /**
     * @param key:key
     * @param code:缓存数据
     * @param cacheTime:缓存时间
     */
    public void setString(String key, String code,Integer cacheTime) {

        if (null!=cacheTime){
            stringRedisTemplate.opsForValue().set(key, code, cacheTime, TimeUnit.SECONDS);
        }else {
            stringRedisTemplate.opsForValue().set(key, code);
        }
    }

    public String getString(String key) {
        return stringRedisTemplate.boundValueOps(key).get();
    }

    /**
     * 通过key前缀批量删除缓存（慎用）
     * @param keyPrefix:key前缀字符串
     * @return 删除数目
     */
    public Long deletesByKey(String keyPrefix) {
        Set<String> set =  stringRedisTemplate.keys(keyPrefix+"*");
        return stringRedisTemplate.delete(set);
    }

    /**
     * 通过key删除缓存
     * @param key
     */
    public void deleteStringByKey(String key) {
        stringRedisTemplate.delete(key);
    }
    public void deleteObjectByKey(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 通过key删除缓存
     * @param key
     */
    public void deleteByKey(String key,int code) {
        if (code==0){
            stringRedisTemplate.delete(key);
        }else {
            redisTemplate.delete(key);
        }
    }

    /**
     * 通过key前缀获取缓存
     */
    public List<String> getStrings(String prefix ){
        // 获取所有的key
        Set<String> keys = stringRedisTemplate.keys(prefix+"*");
        // 批量获取数据
        return stringRedisTemplate.opsForValue().multiGet(keys);
    }

    /**
     * 缓存时间设值方法
     */
    public int cacheTimeMinuet(int minuet){
        return 60*minuet;
    }
    public int cacheTimeHour(int hour){
        return 60*60*hour;
    }
    public int cacheTimeDay(int day){
        return 60*60*24*day;
    }
    public int cacheTimeMonth(int month){
        return 60*60*24*30*month;
    }

}
